package ipmss.ui.authorities;

import ipmss.entity.authorities.User;
import ipmss.entity.authorities.UserProfile;
import ipmss.security.Authorities;
import ipmss.services.authorities.UsersManagementService;
import ipmss.ui.common.Messages;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.mail.MessagingException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.annotation.Secured;

// TODO: Auto-generated Javadoc
/**
 * The Class UsersManagementViewBean.
 *
 * @author Michał Czarnik
 */
@Named
@Scope("session") 
//@Secured({Authorities.ROLE_USERS_MANAGEMENT})
public class UsersManagementViewBean implements Serializable
{
    
    /** The Constant logger. */
    private static final Logger logger = Logger.getLogger(UsersManagementViewBean.class.getName());

    /** The users management. */
    @Inject
    private UsersManagementService usersManagement;

    /** The users. */
    private List<User> users;

    /** The selected user. */
    private User selectedUser;

    // Add user Data
    /** The firstname. */
    private String firstname = "";

    /** The second name. */
    private String secondName = "";

    /** The surname. */
    private String surname = "";

    /** The email. */
    private String email = "";

    /** The address. */
    private String address = "";

    /** The login. */
    private String login = "";

    // private boolean showUsersList = true;
    
   

    /**
     * Instantiates a new users management view bean.
     */
    public UsersManagementViewBean()
    {
	/*users = new ArrayList<User>();
	User u = new User();
	u.setId(0);
	u.seteMail("asd@ad.pl");
	u.setLogin("sdaf@addddddddddddsdgdfsd.pl");
	UserProfile profile = new UserProfile();
	profile.setFirstName("name");
	u.setProfile(profile);
	users.add(u);
	for (int i = 0; i < 1; i++)
	{
	    u = new User();
	    u.setId(2);
	    u.seteMail("asd@ad.pl22");
	    u.setLogin("sdaf@asd.pl2");
	    profile = new UserProfile();
	    profile.setFirstName("name3");
	    u.setProfile(profile);
	    users.add(u);
	}*/

    }

    
    
    /**
     * Adds the user.
     */
    public void addUser()
    {

	User u = new User();
	UserProfile p = new UserProfile();
	p.setAddress(getAddress());
	p.setFirstName(getFirstname());
	p.setSecondName(getSecondName());
	p.setSurname(getSurname());
	u.setProfile(p);
	u.seteMail(getEmail());
	u.setLogin(getLogin());

	boolean duplicateData = false;
	for (User user : users)
	{
	    if (user.geteMail().equals(getEmail()))
	    {
		FacesMessage msg = Messages.getMessage(FacesMessage.SEVERITY_ERROR, "usersManagementMainView.error.eMailDuplicate");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		duplicateData = true;
	    }
	}
	for (User user : users)
	{
	    if (user.getLogin().equals(getLogin()))
	    {
		FacesMessage msg = Messages.getMessage(FacesMessage.SEVERITY_ERROR, "usersManagementMainView.error.loginDuplicate");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		duplicateData = true;
	    }
	}
	if (duplicateData)
	{
	    RequestContext.getCurrentInstance().addCallbackParam("duplicateData", true);
	    return;
	}

	try
	{
	    usersManagement.createUser(u);
	} catch (org.springframework.orm.jpa.JpaSystemException e)
	{
	    logger.log(Level.WARNING, e.toString());
	    e.printStackTrace();
	    String message = e.getMostSpecificCause().getMessage();
	    if (message.contains("Duplicate entry"))
	    {
		int bIndex = message.indexOf("key '") + 5;
		int eIndex = message.indexOf("'", bIndex);

		if (bIndex != -1 && eIndex != -1)
		{
		    String filedName = message.substring(bIndex, eIndex);
		    if (filedName.equals("login"))
		    {
			FacesMessage msg = Messages.getMessage(FacesMessage.SEVERITY_ERROR, "usersManagementMainView.error.loginDuplicate");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		    } else if (filedName.equals("eMail"))
		    {
			FacesMessage msg = Messages.getMessage(FacesMessage.SEVERITY_ERROR, "usersManagementMainView.error.eMailDuplicate");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		    }

		}
	    }
	    if (duplicateData)
	    {
		RequestContext.getCurrentInstance().addCallbackParam("duplicateData", true);
		return;
	    }
	}

	catch (MessagingException e)
	{
	    logger.log(Level.WARNING, e.toString());
	    e.printStackTrace();
	    return;
	}
	users.add(u);
	// FacesContext.getCurrentInstance().
	// Messages.getMessage("usersManagementMainView.login", new Object
	// []{});
	// ResourceBundle bundle =
	// ResourceBundle.getBundle("msgs");Messages.getString("msgs","usersManagementMainView.login");
	/*
	 * FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
	 * "Login Error", "Invalid credentials");
	 * FacesContext.getCurrentInstance
	 * ().addMessage("usersManagementMainView.login",msg);
	 * RequestContext.getCurrentInstance().addCallbackParam("duplicateData",
	 * true);
	 */
    }

    /**
     * Gets the users.
     *
     * @return the users
     */
    public List<User> getUsers()
    {
	if(users == null)
	    loadUsers();
	return users;
    }
    
    /**
     * Load users.
     */
    public void loadUsers()
    {
	users = usersManagement.getUsers();
    }
    
    /**
     * Delete user.
     */
    public void deleteUser()
    {
	
    }

    /**
     * Update login.
     */
    public void updateLogin()
    {
	if (login.length() < 4)
	{
	    if (email.indexOf("@") >= 1)
	    {
		setLogin(email.substring(0, email.indexOf("@")));
	    }
	}
    }

    /**
     * Clean.
     *
     * @param event the event
     */
    public void clean(CloseEvent event)
    {
	firstname = "";
	secondName = "";
	surname = "";
	email = "";
	address = "";
	login = "";
    }

    /**
     * Sets the users.
     *
     * @param users the new users
     */
    public void setUsers(List<User> users)
    {
	this.users = users;
    }

    /**
     * Gets the selected user.
     *
     * @return the selected user
     */
    public User getSelectedUser()
    {
	return selectedUser;
    }

    /**
     * Sets the selected user.
     *
     * @param selectedUser the new selected user
     */
    public void setSelectedUser(User selectedUser)
    {
	this.selectedUser = selectedUser;
    }

    /**
     * Gets the firstname.
     *
     * @return the firstname
     */
    public String getFirstname()
    {
	return firstname;
    }

    /**
     * Sets the firstname.
     *
     * @param firstname the new firstname
     */
    public void setFirstname(String firstname)
    {
	this.firstname = firstname;
    }

    /**
     * Gets the surname.
     *
     * @return the surname
     */
    public String getSurname()
    {
	return surname;
    }

    /**
     * Sets the surname.
     *
     * @param surname the new surname
     */
    public void setSurname(String surname)
    {
	this.surname = surname;
    }

    /**
     * Gets the email.
     *
     * @return the email
     */
    public String getEmail()
    {
	return email;
    }

    /**
     * Sets the email.
     *
     * @param email the new email
     */
    public void setEmail(String email)
    {
	this.email = email;
    }

    /**
     * Gets the address.
     *
     * @return the address
     */
    public String getAddress()
    {
	return address;
    }

    /**
     * Sets the address.
     *
     * @param address the new address
     */
    public void setAddress(String address)
    {
	this.address = address;
    }

    /**
     * Gets the second name.
     *
     * @return the second name
     */
    public String getSecondName()
    {
	return secondName;
    }

    /**
     * Sets the second name.
     *
     * @param secondName the new second name
     */
    public void setSecondName(String secondName)
    {
	this.secondName = secondName;
    }

    /**
     * Gets the login.
     *
     * @return the login
     */
    public String getLogin()
    {
	return login;
    }

    /**
     * Sets the login.
     *
     * @param login the new login
     */
    public void setLogin(String login)
    {
	this.login = login;
    }

    /*
     * public boolean isShowUsersList() { return showUsersList; }
     * 
     * public void setShowUsersList(boolean showUsersList) { this.showUsersList
     * = showUsersList; }
     */

}
